﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Configuration;

public partial class Default2 : System.Web.UI.Page
{
	#region Event Handlers
	protected void Page_Load(object sender, EventArgs e)
	{
		if (!IsPostBack) BuildTree();
	}
	protected void tv1_SelectedNodeChanged(object sender, EventArgs e)
	{
		if (string.IsNullOrEmpty(tv1.SelectedNode.Value)) return;
		if (tv1.SelectedNode.Value.StartsWith("DZ")) {
			pnlImg.Visible = false;
			pnlDeepZoom.Visible = true;
			string path = tv1.SelectedNode.Value.Substring(2);
			string path2 = "DeepZoom/" + path.Substring(path.LastIndexOf('\\') + 1);
			string[] files = System.IO.Directory.GetFiles(path, "*.html");
			if (files.Length == 0) return;

			pnlDeepZoom.Controls.Clear();
			pnlDeepZoom.Controls.Add(new LiteralControl("<iframe src=\"" + path2 + "/" + files[0].Substring(files[0].LastIndexOf('\\') + 1) + "\" height=\"590\" width=\"690\"></iframe>"));
			string blah = ((LiteralControl)pnlDeepZoom.Controls[0]).Text;
			return; }

		// Not Deep Zoom node; do normal stuff
		pnlImg.Visible = true;
		pnlDeepZoom.Visible = false;
		if (tv1.SelectedNode.ChildNodes.Count == 0 && File.Exists(tv1.SelectedNode.Value) && !Directory.Exists(tv1.SelectedNode.Value)) {
			string ThumbnailFile = KC.Business.Blog.Utils.MapThumbnail(tv1.SelectedNode.Value);
			if (!System.IO.File.Exists(ThumbnailFile))
				KC.Business.Blog.Utils.CreateThumbnail(tv1.SelectedNode.Value, ThumbnailFile, 650);
			hlImg.NavigateUrl = GetVirtualPath(tv1.SelectedNode.Value);
			img.ImageUrl = GetVirtualPath(ThumbnailFile);
			img.Style.Remove("border");
			img.Style.Add("border", "none");
			try { PopulateFileInfo(tv1.SelectedNode.Value); }
			catch { } }
	}

	#endregion Event Handlers
	#region Helper Methods

	/// <summary>Builds the image directory tree</summary>
	private void BuildTree()
	{
		tv1.Nodes.Clear();
		tv1.Nodes.Add(BuildNode(ConfigurationManager.AppSettings["Gallery"]));
		tv1.Nodes[0].Text = "Gallery Root";

		// Get/bind/display random node
		List<TreeNode> AllNodes = GetAllNodes(tv1.Nodes[0]);
		TreeNode tn = AllNodes[new Random().Next(0, AllNodes.Count)];
		img.ImageUrl = GetVirtualPath(tn.Value);
		hlImg.NavigateUrl = GetVirtualPath(tn.Value);
		img.Style.Remove("border");
		img.Style.Add("border", "none");
		PopulateFileInfo(tn.Value); 
		tv1.CollapseAll();
		tv1.Nodes.Add(BuildDeepZoom(ConfigurationManager.AppSettings["DeepZoom"]));
	}
	/// <summary>Gets the first leaf in the tree</summary>
	/// <param name="tn">Root (where do I start?)</param>
	/// <returns>First leaf of any node subtree</returns>
	private TreeNode GetFirstNode(TreeNode tn)
	{
		foreach (TreeNode tn2 in tn.ChildNodes)
			if (tn2.ChildNodes.Count > 0) return GetFirstNode(tn2); else return tn2;
		return null;
	}
	/// <summary>Recursively builds a node and all its children</summary>
	/// <param name="path">Physical Path to start</param>
	/// <returns>Build treenode</returns>
	private TreeNode BuildNode(string path)
	{
		TreeNode node = new TreeNode();
		node.Text = path.Substring(path.LastIndexOf('\\') + 1).ToLower(); // Leaf folder name
		node.Value = path;
		node.ToolTip = GetVirtualPath(path);
		foreach (string path2 in Directory.GetDirectories(path))
			node.ChildNodes.Add(BuildNode(path2));
		List<string> files = Directory.GetFiles(path, "*.jpg").ToList<string>();
		files.AddRange(Directory.GetFiles(path, "*.tif").ToList<string>());
		files.AddRange(Directory.GetFiles(path, "*.png").ToList<string>());
		
		foreach (string path2 in files) {
			if (path2.ToLower().Contains("_sm.")) continue;
			TreeNode tn2 = new TreeNode(path2.Substring(path2.LastIndexOf('\\') + 1), path2);
			tn2.ToolTip = GetVirtualPath(tn2.Value);
			if (tn2.Text.Contains("."))
				tn2.Text = tn2.Text.Substring(0, tn2.Text.LastIndexOf('.'));
			node.ChildNodes.Add(tn2);
		}
		return node;
	}
	public string GetPhysicalPath(string VirtualPath)
	{
		// strip leading "gallery\"
		string path = VirtualPath.Substring(VirtualPath.IndexOf('\\'));
		return Path.Combine(ConfigurationManager.AppSettings["Gallery"], Path.GetFileName(path));
		
	}
	public string GetVirtualPath(string PhysicalPath)
	{
		return  "Gallery\\" + PhysicalPath.Replace(ConfigurationManager.AppSettings["Gallery"], "");
	}
	/// <summary>Expands all nodes in a tree which aren't leaves (i.e. those who have children)</summary>
	/// <param name="tn"></param>
	private void ExpandNonLeafNodes(TreeNode tn)
	{
		foreach (TreeNode tn2 in tn.ChildNodes)
			ExpandNonLeafNodes(tn2);
		if (Directory.Exists(tn.Value) && Directory.GetDirectories(tn.Value).Length > 0) tn.Expand(); else tn.Collapse();
	}
	private void PopulateFileInfo(string filename)
	{
		FileInfo fi = new FileInfo(filename);
		using (System.Drawing.Image img = System.Drawing.Image.FromFile(filename))
			lblInfo.Text =
				filename.Substring(filename.LastIndexOf('\\') + 1) + "<br />" +
				"File&nbsp;size:&nbsp;" + fi.Length.ToString("###,###,###,###") + "&nbsp;bytes<br />" +
				"Dimensions:&nbsp;" + img.Width.ToString("###,###,###") + "&nbsp;x&nbsp;" + img.Height.ToString("###,###,###") + "<br />" +
				(((double)(img.Width)) / 200 / 12).ToString("##0.#") + "' x " +
				(((double)(img.Height)) / 200 / 12).ToString("##0.#") + "' @ 200 DPI <br />" +
				((double)img.Width * (double)img.Height / (double)1000000).ToString("##,###.##") + " Megapixels";
	}

	private List<TreeNode> GetAllNodes(TreeNode root)
	{
		if (root.ChildNodes.Count == 0) return new List<TreeNode>() { root };

		List<TreeNode> tn = new List<TreeNode>();
		foreach (TreeNode n in root.ChildNodes) {
			tn.AddRange(GetAllNodes(n));
			tn.Add(n); }
		return tn;
	}

	private TreeNode BuildDeepZoom(string PhysicalPath)
	{
		TreeNode tn = new TreeNode("Deep Zoom", "");
		foreach (string dir in Directory.GetDirectories(PhysicalPath))
			tn.ChildNodes.Add(new TreeNode(dir.Substring(dir.TrimEnd(new char[] { '\\' }).LastIndexOf('\\') + 1).ToLower(), "DZ" + dir));
		return tn;
	}


	#endregion Helper Methods
}